// 应用配置
const APP_CONFIG = {
  storage: {
    dbName: 'YeyingRecordDB',
    version: 1,
    stores: {
      students: 'students',
      classes: 'classes',
      homework: 'homework',
      tasks: 'tasks',
      images: 'images',
      notifications: 'notifications'
    }
  }
}

// IndexedDB 存储服务
export class StorageService {
  private db: IDBDatabase | null = null
  private dbName = APP_CONFIG.storage.dbName
  private version = APP_CONFIG.storage.version

  // 初始化数据库
  async init(): Promise<void> {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open(this.dbName, this.version)

      request.onerror = () => {
        reject(new Error('Failed to open IndexedDB'))
      }

      request.onsuccess = () => {
        this.db = request.result
        resolve()
      }

      request.onupgradeneeded = (event) => {
        const db = (event.target as IDBOpenDBRequest).result

        // 创建学生表
        if (!db.objectStoreNames.contains(APP_CONFIG.storage.stores.students)) {
          const studentStore = db.createObjectStore(APP_CONFIG.storage.stores.students, {
            keyPath: 'id'
          })
          studentStore.createIndex('classId', 'classId', { unique: false })
          studentStore.createIndex('studentNumber', 'studentNumber', { unique: true })
        }

        // 创建班级表
        if (!db.objectStoreNames.contains(APP_CONFIG.storage.stores.classes)) {
          const classStore = db.createObjectStore(APP_CONFIG.storage.stores.classes, {
            keyPath: 'id'
          })
          classStore.createIndex('teacherId', 'teacherId', { unique: false })
        }

        // 创建作业表
        if (!db.objectStoreNames.contains(APP_CONFIG.storage.stores.homework)) {
          const homeworkStore = db.createObjectStore(APP_CONFIG.storage.stores.homework, {
            keyPath: 'id'
          })
          homeworkStore.createIndex('studentId', 'studentId', { unique: false })
          homeworkStore.createIndex('classId', 'classId', { unique: false })
          homeworkStore.createIndex('status', 'status', { unique: false })
        }

        // 创建教学任务表
        if (!db.objectStoreNames.contains(APP_CONFIG.storage.stores.tasks)) {
          const taskStore = db.createObjectStore(APP_CONFIG.storage.stores.tasks, {
            keyPath: 'id'
          })
          taskStore.createIndex('classId', 'classId', { unique: false })
          taskStore.createIndex('subject', 'subject', { unique: false })
          taskStore.createIndex('status', 'status', { unique: false })
        }

        // 创建图片表
        if (!db.objectStoreNames.contains(APP_CONFIG.storage.stores.images)) {
          const imageStore = db.createObjectStore(APP_CONFIG.storage.stores.images, {
            keyPath: 'id'
          })
          imageStore.createIndex('homeworkId', 'homeworkId', { unique: false })
        }

        // 创建通知表
        if (!db.objectStoreNames.contains(APP_CONFIG.storage.stores.notifications)) {
          const notificationStore = db.createObjectStore(APP_CONFIG.storage.stores.notifications, {
            keyPath: 'id'
          })
          notificationStore.createIndex('userId', 'userId', { unique: false })
          notificationStore.createIndex('type', 'type', { unique: false })
          notificationStore.createIndex('isRead', 'isRead', { unique: false })
        }
      }
    })
  }

  // 通用添加方法
  async add<T>(storeName: string, data: T): Promise<void> {
    if (!this.db) throw new Error('Database not initialized')

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([storeName], 'readwrite')
      const store = transaction.objectStore(storeName)
      const request = store.add(data)

      request.onsuccess = () => resolve()
      request.onerror = () => reject(request.error)
    })
  }

  // 通用更新方法
  async update<T>(storeName: string, data: T): Promise<void> {
    if (!this.db) throw new Error('Database not initialized')

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([storeName], 'readwrite')
      const store = transaction.objectStore(storeName)
      const request = store.put(data)

      request.onsuccess = () => resolve()
      request.onerror = () => reject(request.error)
    })
  }

  // 通用获取方法
  async get<T>(storeName: string, id: string): Promise<T | null> {
    if (!this.db) throw new Error('Database not initialized')

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([storeName], 'readonly')
      const store = transaction.objectStore(storeName)
      const request = store.get(id)

      request.onsuccess = () => {
        resolve(request.result || null)
      }
      request.onerror = () => reject(request.error)
    })
  }

  // 通用获取所有方法
  async getAll<T>(storeName: string): Promise<T[]> {
    if (!this.db) throw new Error('Database not initialized')

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([storeName], 'readonly')
      const store = transaction.objectStore(storeName)
      const request = store.getAll()

      request.onsuccess = () => {
        resolve(request.result || [])
      }
      request.onerror = () => reject(request.error)
    })
  }

  // 通用删除方法
  async delete(storeName: string, id: string): Promise<void> {
    if (!this.db) throw new Error('Database not initialized')

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([storeName], 'readwrite')
      const store = transaction.objectStore(storeName)
      const request = store.delete(id)

      request.onsuccess = () => resolve()
      request.onerror = () => reject(request.error)
    })
  }

  // 按索引查询
  async getByIndex<T>(storeName: string, indexName: string, value: any): Promise<T[]> {
    if (!this.db) throw new Error('Database not initialized')

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([storeName], 'readonly')
      const store = transaction.objectStore(storeName)
      const index = store.index(indexName)
      const request = index.getAll(value)

      request.onsuccess = () => {
        resolve(request.result || [])
      }
      request.onerror = () => reject(request.error)
    })
  }
}

// 创建单例实例
export const storageService = new StorageService()
